package com.icetec.iceintel.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.icetec.R;
import com.icetec.iceintel.database.GroupControlSqlHelper;
import com.icetec.iceintel.model.Device;
import com.icetec.iceintel.netrequest.UniResAllocator;

import java.util.ArrayList;

/**
 * Created by 坤道 on 2015/5/24.
 */
public class GroupDeviceAdapter extends BaseAdapter {
    private Context context;
    private Device group;
    private ArrayList<Device> deviceArrayList;
    private GroupControlSqlHelper groupControlSqlHelper;

    public GroupDeviceAdapter(Context context, Device group){
        this.context = context;
        this.group = group;
        groupControlSqlHelper = new GroupControlSqlHelper();
        deviceArrayList = groupControlSqlHelper.getAllDevice(group);
    }

    public void updateFromDb(){
        deviceArrayList = groupControlSqlHelper.getAllDevice(group);
        this.notifyDataSetChanged();
    }

    public void deleteDevice(){
        groupControlSqlHelper.deledeSingleDevice(group);
    }

    @Override
    public int getCount() {
        return deviceArrayList.size();
    }

    @Override
    public Device getItem(int position) {
        return deviceArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return deviceArrayList.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final DeviceHolder deviceHolder;
        Device device = getItem(position);
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.component_group_devicelist_items, null);
            deviceHolder = new DeviceHolder();
            deviceHolder.deviceIcon = (ImageView)convertView.findViewById(R.id.scheme_devicelist_icon_iv);
            deviceHolder.deviceName = (TextView)convertView.findViewById(R.id.group_devicelist_name_tv);
            convertView.setTag(deviceHolder);
        }else{
            deviceHolder = (DeviceHolder)convertView.getTag();
        }

        if(device.getOnoff()!=null&&device.getOnoff().equals("on")){

            deviceHolder.deviceIcon.setImageDrawable(UniResAllocator.getResIDbyType(device.getType(), true));

        }

        else {

            deviceHolder.deviceIcon.setImageDrawable(UniResAllocator.getResIDbyType(device.getType(),false));
        }

        if(device.getName()!=null) {
            deviceHolder.deviceName.setText(device.getName());

        }


        else {
            deviceHolder.deviceName.setText(R.string.unnamed_light);
        }

        return convertView;
    }

    class DeviceHolder{
        ImageView deviceIcon;
        TextView deviceName;
    }
}
